package com.kly.chatter.api.application.task;

import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSONObject;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.google.common.collect.Maps;
import com.kly.chatter.api.application.service.ChatterImRewardService;
import com.kly.chatter.api.application.service.PrivateUnlockRewardService;
import com.kly.chatter.db.dao.ChatterDashboardInfoDao;
import com.kly.chatter.db.entity.ChatterDashboardInfoEntity;
import com.kly.sc.api.application.utils.RpcUtils;
import com.kly.user.chatterService.ChatterUserService;
import com.kly.user.dto.UserInfoDto;
import com.kly.user.dto.chatter.response.ChatterDashboardDto;
import com.kly.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 每日dashboard统计
 */
@Slf4j
@Component
public class DashboardTask {

    @Autowired
    private ChatterDashboardInfoDao chatterDashboardInfoDao;

    @Autowired
    private PrivateUnlockRewardService privateUnlockRewardService;

    @Autowired
    private ChatterImRewardService chatterImRewardService;

    @Resource
    private UserService userService;

    @Resource
    private ChatterUserService chatterUserService;
    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();


    @Scheduled(fixedDelay = 15000)
    public void execute() {

        if (!taskJobExecutor.contains(localIP)) {
            log.info("=============DashboardTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        List<UserInfoDto> chatterList = RpcUtils.getResult(userService.getUserByUserType("1"));
        for (UserInfoDto chatter : chatterList) {

            if(chatter.getUserCode().equals("310456997264752854")){
                log.info("==== DashboardTask 310456997264752854 begin");
            }

            ChatterDashboardInfoEntity chatterDashboardInfo = new ChatterDashboardInfoEntity();
            chatterDashboardInfo.setUserCode(chatter.getUserCode());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Integer date = Integer.parseInt(sdf.format(new Date()));
            chatterDashboardInfo.setOnDate(date);
            ChatterDashboardDto chatterDashboardDto = RpcUtils.getResult(chatterUserService.getChatterDashboardInfo(null, chatter.getUserCode()));
            if (chatterDashboardDto != null) {
                //当天会话数
                chatterDashboardInfo.setChats(chatterDashboardDto.getChats());
                //新会话数
                chatterDashboardInfo.setNewChats(chatterDashboardDto.getNewChats());
                //及时率
                chatterDashboardInfo.setTimelyResponseRate(BigDecimal.valueOf(chatterDashboardDto.getTimelyResponseRate()));
                chatterDashboardInfo.setTimelyResponseLimit(50);
                //在线率
                chatterDashboardInfo.setOnlineRate(BigDecimal.valueOf(chatterDashboardDto.getOnlineRate()));
                //承接率
                chatterDashboardInfo.setAcceptanceRate(BigDecimal.valueOf(chatterDashboardDto.getAcceptanceRate()));
                chatterDashboardInfo.setAcceptanceLimit(80);
            }
            Integer privatePhotosCount = privateUnlockRewardService.getUnlockNum(chatter.getUserCode(), date, 1);
            chatterDashboardInfo.setPrivatePhotosCount(privatePhotosCount);
            Integer privateVideosCount = privateUnlockRewardService.getUnlockNum(chatter.getUserCode(), date, 2);
            chatterDashboardInfo.setPrivateVideosCount(privateVideosCount);
            Map<String, Object> params = Maps.newHashMap();
            params.put("userCode", chatter.getUserCode());
            params.put("onDate", date);
            List<ChatterDashboardInfoEntity> chatterDashboardInfoEntities = chatterDashboardInfoDao.selectByParams(params);
            if (chatterDashboardInfoEntities.isEmpty()) {
                chatterDashboardInfoDao.insert(chatterDashboardInfo);
            } else {
                chatterDashboardInfo.setId(chatterDashboardInfoEntities.get(0).getId());
                chatterDashboardInfoDao.updateByPrimaryKey(chatterDashboardInfo);
            }
        }
    }

    /**
     * 核对前一天的数据
     */
    @Scheduled(cron = "0 0 2 * * ?")
//    @Scheduled(fixedDelay = 15000)
    public void check() {

        if (!taskJobExecutor.contains(localIP)) {
            log.info("=============DashboardTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        List<UserInfoDto> chatterList = RpcUtils.getResult(userService.getUserByUserType("1"));
        for (UserInfoDto chatter : chatterList) {
            ChatterDashboardInfoEntity chatterDashboardInfo = new ChatterDashboardInfoEntity();
            chatterDashboardInfo.setUserCode(chatter.getUserCode());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Integer date = Integer.parseInt(sdf.format(DateUtil.offsetDay(new Date(), -1)));
            chatterDashboardInfo.setOnDate(date);
            ChatterDashboardDto chatterDashboardDto = RpcUtils.getResult(chatterUserService.getChatterDashboardInfo(null, chatter.getUserCode()));
            if (chatterDashboardDto != null) {
                //当天会话数
                chatterDashboardInfo.setChats(chatterDashboardDto.getChats());
                //新会话数
                chatterDashboardInfo.setNewChats(chatterDashboardDto.getNewChats());
                //及时率
                chatterDashboardInfo.setTimelyResponseRate(BigDecimal.valueOf(chatterDashboardDto.getTimelyResponseRate()));
                chatterDashboardInfo.setTimelyResponseLimit(50);
                //在线率
                chatterDashboardInfo.setOnlineRate(BigDecimal.valueOf(chatterDashboardDto.getOnlineRate()));
                //承接率
                chatterDashboardInfo.setAcceptanceRate(BigDecimal.valueOf(chatterDashboardDto.getAcceptanceRate()));
                chatterDashboardInfo.setAcceptanceLimit(80);
            }
            Integer privatePhotosCount = privateUnlockRewardService.getUnlockNum(chatter.getUserCode(), date, 1);
            if (privatePhotosCount != null) {
                chatterDashboardInfo.setPrivatePhotosCount(privatePhotosCount);
            }
            Integer privateVideosCount = privateUnlockRewardService.getUnlockNum(chatter.getUserCode(), date, 2);
            if (privateVideosCount != null) {
                chatterDashboardInfo.setPrivateVideosCount(privateVideosCount);
            }

            if(chatter.getUserCode().equals("310456997264752854")){
                log.info("==== DashboardTask 310456997264752854  privateVideosCount {}", privateVideosCount);
                log.info("==== DashboardTask 310456997264752854  param {}", JSONObject.toJSONString(chatterDashboardInfo));
            }

            Map<String, Object> params = Maps.newHashMap();
            params.put("userCode", chatter.getUserCode());
            params.put("onDate", date);
            List<ChatterDashboardInfoEntity> chatterDashboardInfoEntities = chatterDashboardInfoDao.selectByParams(params);
            if (chatterDashboardInfoEntities.isEmpty()) {
                chatterDashboardInfoDao.insert(chatterDashboardInfo);
            } else {
                chatterDashboardInfo.setId(chatterDashboardInfoEntities.get(0).getId());
                chatterDashboardInfoDao.updateByPrimaryKey(chatterDashboardInfo);
            }
            if(chatter.getUserCode().equals("310456997264752854")){
                log.info("==== DashboardTask 310456997264752854  end");
            }
        }
    }

}
